import os
import tqdm

# 定义字节转 GB 的函数
def bytes_to_gb(bytes_size):
    return bytes_size / (1024 ** 3)

def get_folder_size(folder_path):
    total_size = 0
    file_count = sum(len(files) for _, _, files in os.walk(folder_path))
    with tqdm.tqdm(total=file_count, desc=f"计算 {os.path.basename(folder_path)} 大小", unit=' 文件') as pbar:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                try:
                    total_size += os.path.getsize(file_path)
                except Exception as e:
                    print(f"获取文件 {file_path} 大小失败: {e}")
                pbar.update(1)
    return total_size

def sort_items_by_size(directory):
    items = []
    try:
        entries = os.listdir(directory)
        with tqdm.tqdm(total=len(entries), desc="处理项目", unit=' 项') as outer_pbar:
            for entry in entries:
                entry_path = os.path.join(directory, entry)
                if os.path.isfile(entry_path):
                    try:
                        file_size = os.path.getsize(entry_path)
                        items.append((entry, file_size))
                    except Exception as e:
                        print(f"获取文件 {entry} 大小失败: {e}")
                elif os.path.isdir(entry_path):
                    try:
                        folder_size = get_folder_size(entry_path)
                        items.append((entry, folder_size))
                    except Exception as e:
                        print(f"获取文件夹 {entry} 大小失败: {e}")
                outer_pbar.update(1)

        # 按大小从小到大排序
        items.sort(key=lambda x: x[1])

        print("按大小排序（从小到大）:")
        for item_name, size in items:
            size_in_gb = bytes_to_gb(size)
            print(f"{item_name}: {size_in_gb:.3f} GB")

    except FileNotFoundError:
        print(f"指定的目录 {directory} 不存在。")


if __name__ == "__main__":
    # 指定要处理的目录，这里可以修改为你想要的目录路径
    target_directory = input("请输入要处理的目录路径: ")
    sort_items_by_size(target_directory)
